<template>
  <div class="electron-app">
    <ControlPanel :show-controls="showControls" :navigation-state="navigationState" :current-url="navUrl"
      @navigate="handleNavigate" @go-back="handleGoBack" @go-forward="handleGoForward" @refresh="handleRefresh"
      @apply-background="handleApplyBackground" @set-transparent="handleSetTransparent"
      @reset-background="handleResetBackground" @opacity-change="handleOpacityChange" @zoom-change="handleZoomChange"
      @user-agent-change="handleUserAgentChange" @apply-font="handleApplyFont" @reset-font="handleResetFont"
      @clear-all-data="handleClearAllData" @clear-local-storage="handleClearLocalStorage"
      @clear-session-storage="handleClearSessionStorage" @clear-cookies="handleClearCookies" />

    <WebViewContainer ref="webviewRef" :url="currentUrl" :user-agent="userAgent"
      @navigation-state-changed="handleNavigationStateChanged" @dom-ready="handleDomReady"
      @new-window="handleNewWindow" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, provide, reactive } from 'vue'
import ControlPanel from './components/ControlPanel.vue'
import WebViewContainer from './components/WebViewContainer.vue'
const backgroundConfig = reactive({
  color: 'transparent',
  opacity: 1
});
provide('backgroundConfig', backgroundConfig);
const fontConfig = reactive({
  family: 'pingFang SC',
  size: 16,
  weight: 'normal'
});
provide('fontConfig', fontConfig);
const zoom = ref(1);
provide('zoom', zoom);
const opacity = ref(1);
provide('opacity', opacity);

// ========================================================================================
// 响应式数据定义 (Reactive Data)
// ========================================================================================

// 控制面板状态
const showControls = ref(true)

// 导航状态
const navigationState = ref({
  canGoBack: false,
  canGoForward: false
})

// WebView相关状态
const webviewRef = ref()
const currentUrl = ref('https://bing.com')
const userAgent = ref("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36")

// CSS管理
const injectedCSSKeys = ref(new Set())
const fontCSSKey = ref(null)

// ========================================================================================
// 工具函数 (Utility Functions)
// ========================================================================================

/**
 * 将十六进制颜色转换为RGBA格式
 */
function hexToRgba(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

// ========================================================================================
// 事件处理函数 (Event Handlers)
// ========================================================================================

const navUrl = ref(currentUrl.value);
// 导航相关事件
function handleNavigate(url) {
  currentUrl.value = url
}

function handleGoBack() {
  if (webviewRef.value) {
    webviewRef.value.goBack()
  }
}

function handleGoForward() {
  if (webviewRef.value) {
    webviewRef.value.goForward()
  }
}

function handleRefresh() {
  if (webviewRef.value) {
    webviewRef.value.reload()
  }
}

function handleNavigationStateChanged(state) {
  navigationState.value = state
}

async function handleDomReady(params) {
  const { url } = params;
  // 更新当前URL显示
  if (url) {
    navUrl.value = url
  }

  // 延迟注入初始CSS样式
  // setTimeout(async () => {
  if (webviewRef.value) {
    const cssKey = await webviewRef.value.insertCSS(`
        ::-webkit-scrollbar {
          display: none !important;
        }
        *{
          border:none !important;
          background:${backgroundConfig.color} !important;
        }
      `)
    injectedCSSKeys.value.add(cssKey)
  }
  handleApplyFont(fontConfig)
  // }, 600)
}

function handleNewWindow(e) {
  console.log('新窗口事件:', e)
}

// 背景颜色相关事件
async function handleApplyBackground(color) {
  if (!webviewRef.value) return

  try {
    const cssKey = await webviewRef.value.insertCSS(`
      * {
        background: ${color} !important;
      }
    `)
    injectedCSSKeys.value.add(cssKey)
  } catch (error) {
    console.error('应用背景颜色失败:', error)
  }
}

async function handleSetTransparent() {
  await handleApplyBackground('transparent')
}

async function handleResetBackground() {
  if (!webviewRef.value) return

  try {
    for (const key of injectedCSSKeys.value) {
      await webviewRef.value.removeInsertedCSS(key)
    }
    injectedCSSKeys.value.clear()
  } catch (error) {
    console.error('重置背景失败:', error)
  }
}

// 透明度相关事件
async function handleOpacityChange(opacity) {
  try {
    const actualOpacity = await window.electron.ipcRenderer.invoke('set-opacity', opacity)
    console.log('实际设置的透明度:', actualOpacity)
  } catch (error) {
    console.error('设置透明度失败:', error)
  }
}

// 缩放相关事件
function handleZoomChange(zoom) {
  if (webviewRef.value) {
    webviewRef.value.setZoomFactor(zoom)
  }
}

// 用户代理相关事件
function handleUserAgentChange(newUserAgent) {
  userAgent.value = newUserAgent
}

// 字体相关事件
async function handleApplyFont(fontConfig) {
  if (!webviewRef.value) return

  try {
    // 如果之前有应用过字体，先移除
    if (fontCSSKey.value) {
      await webviewRef.value.removeInsertedCSS(fontCSSKey.value)
      fontCSSKey.value = null
    }

    // 构建字体样式
    let fontFamily = fontConfig.family
    if (fontFamily) {
      // 如果字体名包含空格或中文，添加引号
      if (fontFamily.includes(' ') || /[\u4e00-\u9fa5]/.test(fontFamily)) {
        fontFamily = `"${fontFamily}"`
      }
    }

    const fontCSS = `
      * {
        ${fontFamily ? `font-family: ${fontFamily}, sans-serif !important;` : ''}
        font-size: ${fontConfig.size}px !important;
        font-weight: ${fontConfig.weight} !important;
      }
      
      input, textarea, select, button {
        ${fontFamily ? `font-family: ${fontFamily}, sans-serif !important;` : ''}
        font-size: ${fontConfig.size}px !important;
        font-weight: ${fontConfig.weight} !important;
      }
    `

    // 注入字体样式
    fontCSSKey.value = await webviewRef.value.insertCSS(fontCSS)
    injectedCSSKeys.value.add(fontCSSKey.value)

    console.log('字体样式已应用:', fontConfig)

  } catch (error) {
    console.error('应用字体失败:', error)
  }
}

async function handleResetFont() {
  if (!webviewRef.value) return

  try {
    // 移除字体CSS
    if (fontCSSKey.value) {
      await webviewRef.value.removeInsertedCSS(fontCSSKey.value)
      injectedCSSKeys.value.delete(fontCSSKey.value)
      fontCSSKey.value = null
    }

    console.log('字体设置已重置')

  } catch (error) {
    console.error('重置字体失败:', error)
  }
}

// 数据清理相关事件
async function handleClearLocalStorage() {
  if (!webviewRef.value) return

  try {
    await webviewRef.value.executeJavaScript(`
      localStorage.clear();
      console.log('本地存储已清除');
    `)
    console.log('本地存储清除成功')
  } catch (error) {
    console.error('清除本地存储失败:', error)
  }
}

async function handleClearSessionStorage() {
  if (!webviewRef.value) return

  try {
    await webviewRef.value.executeJavaScript(`
      sessionStorage.clear();
      console.log('会话存储已清除');
    `)
    console.log('会话存储清除成功')
  } catch (error) {
    console.error('清除会话存储失败:', error)
  }
}

async function handleClearCookies() {
  if (!webviewRef.value) return

  try {
    // 通过JavaScript清除当前域的Cookie
    await webviewRef.value.executeJavaScript(`
      document.cookie.split(";").forEach(function(c) { 
        document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
      });
      console.log('Cookie已清除');
    `)

    // 如果可以访问webContents，也可以通过Electron API清除
    try {
      const webContents = webviewRef.value.getWebContents()
      if (webContents && webContents.session) {
        await webContents.session.clearStorageData({
          storages: ['cookies']
        })
      }
    } catch (electronError) {
      console.log('Electron API清除Cookie失败，但JavaScript清除可能已成功:', electronError)
    }

    console.log('Cookie清除成功')
  } catch (error) {
    console.error('清除Cookie失败:', error)
  }
}

async function handleClearAllData() {
  if (!webviewRef.value) return

  try {
    // 通过JavaScript清除所有存储数据
    await webviewRef.value.executeJavaScript(`
      // 清除localStorage
      localStorage.clear();
      
      // 清除sessionStorage
      sessionStorage.clear();
      
      // 清除Cookie
      document.cookie.split(";").forEach(function(c) { 
        document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
      });
      
      console.log('所有数据已清除：localStorage, sessionStorage, cookies');
    `)

    // 如果可以访问webContents，通过Electron API进行更彻底的清除
    try {
      const webContents = webviewRef.value.getWebContents()
      if (webContents && webContents.session) {
        await webContents.session.clearStorageData({
          storages: ['cookies', 'localstorage', 'sessionstorage', 'websql', 'indexdb', 'cachestorage']
        })
      }
    } catch (electronError) {
      console.log('Electron API清除失败，但JavaScript清除可能已成功:', electronError)
    }

    console.log('所有数据清除成功')

    // 可选：刷新页面以确保清除生效
    setTimeout(() => {
      handleRefresh()
    }, 500)

  } catch (error) {
    console.error('清除所有数据失败:', error)
  }
}

// ========================================================================================
// 生命周期钩子 (Lifecycle Hooks)
// ========================================================================================

onMounted(() => {
  // 设置IPC监听器
  window.electron.ipcRenderer.on('toggle-controls', () => {
    showControls.value = !showControls.value
  })
})

onBeforeUnmount(() => {
  // 移除IPC监听器
  window.electron.ipcRenderer.removeAllListeners('toggle-controls')
})
</script>

<style scoped>
.electron-app {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: transparent;
  position: relative;
}
</style>